﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;

public partial class MutasiBarang2 : System.Web.UI.Page
{
    private static string strConn = ConfigurationManager.ConnectionStrings["LabConnectionString"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        populateBarang();
        populateLabAsal();
        populateTahunAnggaran();
    }

    private void populateBarang()
    {
        string query = "sp_namabarang_list";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        lstBarang.DataSource = dt;
        lstBarang.DataBind();
    }

    private void populateLabAsal()
    {
        string query = "sp_namalab_list";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        lstLabAsal.DataSource = dt;
        lstLabAsal.DataBind();
    }

    private void populateTahunAnggaran()
    {
        string query = "sp_get_tahun_anggaran";
        DataTable dt = new DataTable();
        using (SqlDataAdapter da = new SqlDataAdapter(query, strConn))
        {
            da.Fill(dt);
        }
        DataTable tahun = new DataTable();
        tahun.Columns.Add("TAHUN");
        if (dt.Rows.Count > 0)
        {
            int min = int.Parse(dt.Rows[0]["TAHUN1"].ToString());
            int max = int.Parse(dt.Rows[0]["TAHUN2"].ToString());
            for (int i = min; i <= max; i++)
            {
                DataRow dr = tahun.NewRow();
                dr["TAHUN"] = i;
                tahun.Rows.Add(dr);
            }
        }
        lstTahunAnggaran.DataSource = tahun;
        lstTahunAnggaran.DataBind();
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> files = new Dictionary<string, string>();
        foreach (string item in Request.Files.Keys)
        {
            HttpPostedFile file = Request.Files[item];
            if (file.ContentLength > 0)
            {
                string originalFilename = file.FileName;
                string extension = Path.GetExtension(file.FileName);
                string newFilename = Guid.NewGuid().ToString() + extension;
                string targetPath = Server.MapPath(@"~\UploadedFiles\" + newFilename);
                file.SaveAs(targetPath);
                files[originalFilename] = newFilename;
            }
        }

        string uploadedFiles = string.Empty;
        foreach (string item in files.Keys)
        {
            uploadedFiles += item + "," + files[item] + "|";
        }

        mutasi(Request.Form["barang"], Request.Form["tahun"], Request.Form["jumlah"], Request.Form["labAsal"], Request.Form["alasan"], Request.Form["keterangan"], Request.Form["user"], uploadedFiles);
    }

    private void showMessage(string caption, string message, string type)
    {
        message = message.Replace("'", "&apos;");
        message = message.Replace(Environment.NewLine, "<br />");
        string clientScript = "$(document).ready(function(){ new PNotify({ title: '" + caption + "', text: '" + message + "', type: '" + type + "',styling: 'bootstrap3' }); });";
        ScriptManager.RegisterStartupScript(Page, this.GetType(), "ShowMessage", clientScript, true);
    }

    private void mutasi(string barang, string tahun, string jumlah, string labAsal, string alasan, string keterangan, string user, string files)
    {
        using (SqlConnection cn = new SqlConnection(strConn))
        {
            cn.Open();
            string query = "sp_barang_mutasi2 {0}, {1}, {2}, {3}, '{4}', '{5}', {6}, '{7}'";
            using (SqlCommand cmd = new SqlCommand(string.Format(query, barang, tahun, jumlah, labAsal, alasan, keterangan, user, files), cn))
            {
                try
                {
                    int ra = cmd.ExecuteNonQuery();
                    if (ra > 0)
                    {
                        //this.namaLab.Value = string.Empty;
                        showMessage("Sukses melakukan mutasi barang", "Barang <b>" + alasan + "</b> berhasil dicatat.", "success");
                    }
                    else
                    {
                        showMessage("Gagal melakukan mutasi barang", "Tidak ada data yang ditambahkan", "error");
                    }
                }
                catch (Exception ex)
                {
                    string msg = ex.Message;
                    showMessage("Gagal melakukan mutasi barang", msg, "error");
                }
            }
        }
    }
}